package com.david.mydemo.ctl_ocr.ocr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.david.mydemo.ctl_ocr.service.HttpPostGatewayService;
import com.david.mydemo.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.Response;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Slf4j
public class WebUocr {

    private static final String file = "D:\\develop\\ocr\\img0.png";
    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json;charset=utf-8");

    //api网关path映射字段
    private static final String path = "/aiability/v1/ocr";
    //授权标识;使用您申请的appid
    private static final String appid = "5o1efz3y";
    //授权密钥;使用您申请的appkey
    private static final String appkey = "45fb777278e9396fc3761ef6dd728fe7";
    private static final String ocrBaseUrl = "http://117.132.181.235:9050";

    public static byte[] file2byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            log.error("文件转换字节数据报错", e);
        }
        return buffer;
    }

    /**
     * 解析提取图片文字列表
     * @param filePath 图片路径
     * @param ocrBaseUrl ocr服务
     * @param path api网关path映射字段
     * @param appid 授权标识;使用您申请的appid
     * @param appkey 授权密钥;使用您申请的appkey
     * @return
     */
    public static List<String> pickupTextFromImg(String filePath, String ocrBaseUrl, String path, String appid, String appkey) {
        UocrReq bodyParam = new UocrReq();
        byte[] picBytes = WebUocr.file2byte(new File(filePath));
        String picData = Base64.getEncoder().encodeToString(picBytes);
        bodyParam.setPicData(picData);
        UocrResp uocrResp = null;
        try {
            Response response = new HttpPostGatewayService().recongize(ocrBaseUrl, path, appid, appkey, "", bodyParam);
            log.info("调用OCR接口返回数据：url:{}, response:{}", ocrBaseUrl, response.body());
            uocrResp = JSON.parseObject(response.body().string(), UocrResp.class);
        } catch (IOException e) {
            log.error("解析图片内容报错，错误信息：", e);
            return null;
        }
        JSONArray pages = JSONObject.parseObject(uocrResp.getResult()).getJSONArray("pages");
        String allwords = "";
        List<String> matchWords = new ArrayList<>();
        for (int i = 0; i < pages.size(); i++) {
            JSONObject page = pages.getJSONObject(i);
            JSONArray lines = page.getJSONArray("lines");
            if (lines == null) {
                continue;
            }
            for (int j = 0; j < lines.size(); j++) {
                JSONObject line = lines.getJSONObject(j);
                JSONArray words = line.getJSONArray("words");
                if (words == null) {
                    continue;
                }
                for (int k = 0; k < words.size(); k++) {
                    String content = words.getJSONObject(k).getString("content");
                    if (StringUtils.isEmpty(content)) {
                        continue;
                    }
                    allwords += content + "\n";
                    matchWords.add(content);
                }
            }
        }
        return matchWords;
    }

    public static void main(String[] args) throws IOException {
        String filePath = "d:/files/8.jpeg";
        UocrReq bodyParam = new UocrReq();
        byte[] picBytes = WebUocr.file2byte(new File(filePath));
        String picData = Base64.getEncoder().encodeToString(picBytes);
        bodyParam.setPicData(picData);
        Response response = new HttpPostGatewayService().recongize(ocrBaseUrl, path, appid, appkey, "", bodyParam);
        log.info("调用OCR接口返回数据：url:{}, response:{}", ocrBaseUrl, response.body());
        UocrResp uocrResp = JSON.parseObject(response.body().string(), UocrResp.class);
        JSONArray pages = JSONObject.parseObject(uocrResp.getResult()).getJSONArray("pages");
        String allwords = "";
        List<String> matchWords = new ArrayList<>();
        boolean yyzzSign = false;
        boolean xxdmSign = false;
        for (int i = 0; i < pages.size(); i++) {
            JSONObject page = pages.getJSONObject(i);
            JSONArray lines = page.getJSONArray("lines");
            if (lines == null) {
                continue;
            }
            for (int j = 0; j < lines.size(); j++) {
                JSONObject line = lines.getJSONObject(j);
                JSONArray words = line.getJSONArray("words");
                if (words == null) {
                    continue;
                }
                for (int k = 0; k < words.size(); k++) {
                    String content = words.getJSONObject(k).getString("content");
                    if (StringUtils.isEmpty(content)) {
                        continue;
                    }
                    allwords += content + "\n";

                    if ("营业执照".equals(content)) {
                        yyzzSign = true;
                        matchWords.add(content);
                    }
                    String pattern = "^[A-Z0-9]+$";
                    if (content.length() == 18 && content.matches(pattern)) {
                        xxdmSign = true;
                        matchWords.add(content);
                    }
                }
            }
        }
        System.out.println("OCR解析的所有字符：" + allwords);
        System.out.println("OCR解析的匹配营业执照字符：");
        if (yyzzSign && xxdmSign) {
            for (String word : matchWords) {
                System.out.println(word);
            }
        }

        System.out.println("91621122MAC25UWNIN".length());
        System.out.println("91621122MAC25UWNIN".matches("^[A-Z0-9]+$"));


    }

}
